package com.springinaction.ch05.web;


import com.springinaction.ch05.Spittle;
import com.springinaction.ch05.data.SpittleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 *
 */
@Controller
@RequestMapping({"/spittles"})
public class SpittleController {
    private SpittleRepository spittleRepository;
    private static final String MAX_LONG_AS_STRING = "9223372036854775807";
    @Autowired
    public SpittleController(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }

    /**
    　* @Description: TODO
    　* @param model 相当于一个map model.addAttribute 默认key是自动是别的 例如下面就是 spittleList
    　* @return String 用来找view.jsp
    　* @throws
    　* @date 18-12-8 下午10:03
    　*/

//    @RequestMapping(method = RequestMethod.GET)
//    public String spittles(Model model) {
//        model.addAttribute(spittleRepository.findSpittles(Long.MAX_VALUE, 20));
//        return "spittles";
//    }

    @RequestMapping(method = RequestMethod.GET)
    public List<Spittle> spittles(
            @RequestParam(value = "max", defaultValue = MAX_LONG_AS_STRING) Long max,
            @RequestParam(value = "count", defaultValue = "20") int count) {

        return spittleRepository.findSpittles(max, count);
    }
    @RequestMapping(value = {"/{spittleId}"}, method = RequestMethod.GET)
    public String showspittle(
           // @PathVariable(value = "spittleId") int spittleId, 或 RequestMapping占位符和参数名一样时可简写
            @PathVariable int spittleId,
            Model model
    ) {
            model.addAttribute(spittleRepository.findOne(spittleId));
            return "spittle";
    }


}
